/*
    This is a set of libraries to assist in OpenGl and Other Applications
    Copyright (C) 2008  The Modular Engine Team

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SERVERMODULE_H
#define SERVERMODULE_H
#include "EngineCore.h"
#include "ConsoleModule.h"
#include "networkData.h"
#include <vector>


#undef CLASSDECL
#ifdef SERVERMODULE
	#define CLASSDECL __declspec(dllexport)
//user32.lib opengl32.lib Gdi32.lib glu32.lib WS2_32.lib
	#pragma comment( lib, "WS2_32.lib" )
#else
	#pragma comment( lib, "ServerModule.lib" )
	#define CLASSDECL __declspec(dllimport)
#endif


namespace ModularEngine
{
	enum SM_WHO
	{
		SM_ALL,
		SM_ONE
	};

	// Class Representing a Client Currently Connected
	class CLASSDECL Client
	{
	public:
		// Client Socket
		SOCKET mClient;	
		// List of unprocessed messages.
		std::list<NetworkMessage> mMessages;
		int mnClientNumber;
		~Client()
		{
			return;
		}

	};

	class CLASSDECL ServerModule: BASE(ServerModule)
	{
	protected:
		int iResult;
		WSADATA wsaData;
		struct addrinfo *result, *ptr, hints;
		
	public:
		int mnCurrClient;
		int nCurrMessageNumber;

		ServerModule()
		{
			processMessage = 0;
		}

		SOCKET ListenSocket;
	
		// Mutex handles for adding clients and processing messages
		HANDLE mClientAdd;
		HANDLE mMessageAdd;

		// Vector List for currently connected clients
		std::vector<Client *> mvClients;
		// Vector List for queued clients
		std::vector<Client *> mvNewClients;

		bool mbHost;
		bool mbRunning;

		int initHost();
		void endHost();

		void sendMessage( NetworkMessage nMsg, int nWho, int nUser );
		void sendMessage( int nMessage, int nWho, int nUser, char *pBuffer = 0, int nSize = 0);

		NetworkMessageProcFunctor *processMessage;

		//void processMessage(NetworkMessages msg);
		//int translateMessage( simpleMessage msg );

		int initialize();
		int run();
	};
}

#endif
